package com.bao.auth.server.demo.monster;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 这个测试类在外网是能正常获取汇联易数据的
 */
@Slf4j
@Service
public class HlyHttpUtilTest {

    public static void main(String[] args) {
        String s = getBaoGan();
        System.out.println(s);
    }


    public static String getToken(){
        String appId = "2a5ca040-8e27-4280-a936-8ce2d09416c7";
        String appSecret = "YjM3NGUxYWQtOTI4OS00NDc2LWEwY2UtNjczMWU4NWQ5MTNh";
        String url = "https://api-byd-prod.huilianyi.com";

        String clientId = appId;//需要替换
        String securet = appSecret;//需要替换
        String tokenUrl = url + "/oauth/token";//需要替换

        RestTemplate restTemplate = initRestTemplate();

        HttpHeaders httpHeaders = new HttpHeaders();
        String authStr = clientId.concat(":").concat(securet);
        String authStrEnc = new String(Base64.getEncoder().encode((authStr.getBytes())));
        httpHeaders.set("Authorization", "Basic ".concat(authStrEnc));
        httpHeaders.set("Content-Type", "application/x-www-form-urlencoded");

        MultiValueMap<String, String> formData = new LinkedMultiValueMap();
        formData.add("grant_type", "client_credentials");
        formData.add("scope", "write");

        HttpEntity httpEntity =  new HttpEntity(formData, httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(tokenUrl, HttpMethod.POST, httpEntity, String.class);
        String respone = exchange.getBody();
        System.out.println(respone);
        return respone;
    }


    /**
     * 获取包干人员信息
     */
    public static String getBaoGan(){
        String hlyurl = "https://api-byd-prod.huilianyi.com";
        RestTemplate restTemplate = initRestTemplate();
        String s = getToken();
        JSONObject jsonObject = JSONObject.parseObject(s);
        String accessToken = jsonObject.getString("access_token");
        int page = 1;
        int size = 500;
        String url = hlyurl + "/api/open/userGroup/BGRY?access_token=" + accessToken +"&page="+ page +"&size=" + size;
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, null,String.class);
            String respone = exchange.getBody();
            JSONArray data = JSONArray.parseArray(respone); 
            Map<String,String> staffCodes = new HashMap<>();
            for(int i = 0;i < data.size(); i++) {
                JSONObject object = data.getJSONObject(i);
                String employeeID = object.getString("employeeID");
                String entryDate = object.getString("entryDate");
                staffCodes.put(employeeID,entryDate);
            }
            System.out.println(respone);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }


    /**
     * 获取差旅补助信息
     * @return
     */
    public static String getTravelAllowanceCal(){
        String hlyurl = "https://api-byd-prod.huilianyi.com";
        RestTemplate restTemplate = initRestTemplate();
        String s = getToken();
        JSONObject jsonObject = JSONObject.parseObject(s);
        String accessToken = jsonObject.getString("access_token");
        int page = 1;
        int size = 50;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal =  Calendar.getInstance();
        cal.add(Calendar.MONTH,-10);
        String startDate = sdf.format(cal.getTime());
        String endDate = sdf.format(new Date());
        Boolean showBankInfo = true;//是否显示银行账户信息
        String url = hlyurl + "/api/open/user?access_token=" + accessToken +"&startDate="+ startDate +"&endDate=" + endDate
                + "&showBankInfo="+ showBankInfo + "&page="+ page +"&size=" + size;
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, null,String.class);
            String respone = exchange.getBody();
            JSONArray data = JSONArray.parseArray(respone);
            System.out.println(respone);
            Map<String, Map<String,String>> map = new HashMap<>();
            for(int i = 0;i < data.size(); i++){
                JSONObject object = data.getJSONObject(i);
                JSONArray bankAccounts = object.getJSONArray("contactBankAccounts");
                String employeeTypeCode = object.getString("employeeTypeCode");
                if(bankAccounts != null && !bankAccounts.isEmpty()){
                    JSONObject accountBank = bankAccounts.getJSONObject(0);
                    String branchName = accountBank.getString("branchName");//开户行名称
                    String bankAccountNo = accountBank.getString("bankAccountNo");//银行账号
                    String bankName = accountBank.getString("bankName");//银行名称
                    String bankCode = accountBank.getString("bankCode");//开户行行号
                    Map<String,String> bank = new HashMap<>();
                    bank.put("branchName",branchName);
                    bank.put("bankAccountNo",bankAccountNo);
                    bank.put("bankName",bankName);
                    bank.put("bankCode",bankCode);

                    map.put(employeeTypeCode,bank);

                }
            }
            if(map != null){

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    private static RestTemplate initRestTemplate() {
        int MAX_TIME_OUT = 1000 * 120;
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(MAX_TIME_OUT);
        httpRequestFactory.setConnectTimeout(MAX_TIME_OUT);
        httpRequestFactory.setReadTimeout(MAX_TIME_OUT);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(httpRequestFactory);
        return restTemplate;
    }


}
